package com.didispace.web;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;


@RestController
public class ComputeController {

    private final Logger logger = Logger.getLogger(getClass());

    @Autowired
    private DiscoveryClient client;

    @RequestMapping(value = "/add" ,method = RequestMethod.GET)
    public Integer add(@RequestParam Integer a, @RequestParam Integer b) {
        ServiceInstance instance = client.getLocalServiceInstance();
        Integer r = a + b;
        logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r);
        return r;
    }
    
    
    @RequestMapping(value = "/get_user" ,method = RequestMethod.GET)
    public String getUserById(String id) {
    	JSONObject jsonObject = new JSONObject();
        ServiceInstance instance = client.getLocalServiceInstance();
    	jsonObject.put("id", id);
		jsonObject.put("name", "Cary");
		JSONObject hostInfo = new JSONObject();//将实际被调用的服务信息返回，用于判断是否有负载均衡
		hostInfo.put("host", instance.getHost());
		hostInfo.put("port", instance.getPort());
		hostInfo.put("uri", instance.getUri());
		jsonObject.put("host_info", hostInfo);
        logger.info("####### host:" + instance.getHost() +"port:"+instance.getPort()+ ", service_id:" + instance.getServiceId());
        return jsonObject.toString();
    }


}